
const db = uniCloud.database()
var jwt = require('jwt_common/node_modules/jwt-simple');
var secret = Buffer.from('fwqd4we64f5sd4b64d14d984', 'hex');
const tokenExp = 30 * 24 * 3600000 / 1000;

exports.main = async (event, context) => {
  	const collection = db.collection('admin')
  	let user
  	if (event.openid) {
  		user = await collection.where({
  			openid: event.openid
  		}).get()

  		if (user.affectedDocs < 1) {
  			// 没有就新增
  			await collection.add({
  				openid: event.openid
  			})
  		}

  		return {
  			code: 0,
  			msg: '登录成功'
  		}
  	} else {
  		user = await collection.where({
  			adminname: event.name,
  			password: event.pwd
  		}).get()

  		if (user.affectedDocs < 1) {
  			return {
  				code: -2,
  				msg: '管理员账号或密码错误'
  			}
  		} else {
			var payload = {
				 user: event.user,
				 exp: Date.now() + tokenExp,
			};
			var token = jwt.encode(payload, secret);
  			return {
				adminname:event.name,
				token:token,
  				code: 0,
  				msg: '登录成功'
  			}
  		}
  	}
}